﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using TaDMS.Models;

namespace TaDMS.Filters
{
    public class TaDMSRoleProvider : RoleProvider
    {
        public string ErrorMessage { get; set; }

        private readonly UnitOfWork _unitOfWork = new UnitOfWork();

        public override bool IsUserInRole(string username, string roleName)
        {

            int? total;
            var user = _unitOfWork.AccountRepository.GetData(total: out total, orderBy: order => order.OrderBy(v => v.Username), filter: v => v.Username.Equals(username), includeProperties: "Role").FirstOrDefault();

            if (user == null)
            {
                ErrorMessage = _unitOfWork.AccountRepository.ErrorMessage;
                return false;
            }

            return user.Role.RoleName.Equals(roleName);

        }

        public override string[] GetRolesForUser(string username)
        {

            int? total;
            var user = _unitOfWork.AccountRepository.GetData(total: out total, orderBy: order => order.OrderBy(v => v.Username), filter: v => v.Username.Equals(username), includeProperties: "Role").FirstOrDefault();

            if (user == null)
            {
                ErrorMessage = _unitOfWork.AccountRepository.ErrorMessage;
                return null;
            }

            return new[] { user.Role.RoleName };

        }

        #region Not Implement Method

        public override void CreateRole(string roleName)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            throw new NotImplementedException();
        }

        public override bool RoleExists(string roleName)
        {
            throw new NotImplementedException();
        }

        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override string[] GetUsersInRole(string roleName)
        {
            throw new NotImplementedException();
        }

        public override string[] GetAllRoles()
        {
            throw new NotImplementedException();
        }

        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            throw new NotImplementedException();
        }

        public override string ApplicationName { get; set; }

        #endregion
    }
}